package com.jzo2o.trade.controller;

import com.jzo2o.api.trade.enums.PayChannelEnum;
import com.jzo2o.trade.model.dto.TradeUpdateDTO;
import com.jzo2o.trade.service.IPayService;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@RestController
@Slf4j
@RequestMapping
public class PayNotifyController {


    @Autowired
    private NotificationConfig notificationConfig;

    @Autowired
    private IPayService payService;

    @RequestMapping("/wxpay/notify")
    public String payNotify(@RequestBody String body, HttpServletRequest request) throws Exception {
        log.info("收到微信回调消息");
        String wechatSignature = request.getHeader("Wechatpay-Signature");
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");

        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(wechatpayNonce)
                .signature(wechatSignature)
                .timestamp(wechatTimestamp)
                .body(body)
                .build();

        // 初始化 NotificationParser
        NotificationParser parser = new NotificationParser(notificationConfig);
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            String outTradeNo = transaction.getOutTradeNo();
            log.info("开始处理订单后续逻辑：{}", outTradeNo);
            //todo
            TradeUpdateDTO tradeUpdateDTO = new TradeUpdateDTO();

            tradeUpdateDTO.setTradingNo(transaction.getOutTradeNo());
            tradeUpdateDTO.setPayChannel(PayChannelEnum.WECHAT_PAY.getValue());
            tradeUpdateDTO.setPayTime(transaction.getSuccessTime());
            tradeUpdateDTO.setTransactionId(transaction.getTransactionId());
            payService.paySuccess(tradeUpdateDTO);
        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).toString();
        }
        // 处理成功，返回 200 OK 状态码
        return ResponseEntity.status(HttpStatus.OK).toString();
    }

    @RequestMapping("/alipay/notify")
    public String alipayNotify(@RequestBody String body, HttpServletRequest request) throws Exception {
        log.info("收到支付宝回调消息");
        String traingingOrderNo = request.getParameter("out_trade_no");
        log.info("开始处理订单后续逻辑：{}", traingingOrderNo);
        TradeUpdateDTO tradeUpdateDTO = new TradeUpdateDTO();
        // 封装支付成功 参数
        tradeUpdateDTO.setTradingNo(traingingOrderNo);
        tradeUpdateDTO.setPayChannel(PayChannelEnum.ALI_PAY.getValue());
        tradeUpdateDTO.setPayTime(LocalDateTime.now().toString());
        // todo
        tradeUpdateDTO.setTransactionId(traingingOrderNo);
        payService.paySuccess(tradeUpdateDTO);
        return ResponseEntity.status(HttpStatus.OK).toString();
    }

}
